<template>
  <el-dialog
    v-dialogDrag
    v-loading="loading"
    append-to-body
    top="6vh"
    width="300"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    :type="type"
    :title="title"
    :visible.sync="isVisible"
  >
    <el-form
      ref="dataForm"
      size="mini"
      :model="dataForm"
      :rules="dataRule"
      label-width="150px"
      @keyup.enter.native="dataFormSubmit()"
    >
      <el-card
        style="margin-bottom:5px;"
        shadow="hover"
      >
        <div
          slot="header"
          class="clearfix cardHeader"
        >
          <span><i class="el-icon-star-on" />基本信息</span>
        </div>
        <el-row
          type="flex"
          class="row-bg"
        >
          <el-col :span="12">
            <el-form-item
              label="学生姓名"
              prop="studentName"
            >
              <el-input
                v-model="dataForm.studentName"
                clearable
                placeholder="学生姓名"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="学籍号"
              prop="studentId"
            >
              <el-input
                v-model="dataForm.studentId"
                clearable
                placeholder="学籍号"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          type="flex"
          class="row-bg"
        >
          <el-col :span="12">
            <el-form-item
              label="身份证号"
              prop="idNumber"
            >
              <el-input
                v-model="dataForm.idNumber"
                clearable
                placeholder="身份证号"
                maxlength="50"
                show-word-limit
                @blur="getBirth(dataForm.idNumber)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="出生日期"
              prop="birthday"
            >
              <el-date-picker
                v-model="dataForm.birthday"
                style="width:100%"
                type="date"
                placeholder="出生日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          type="flex"
          class="row-bg"
        >
          <el-col :span="12">
            <el-form-item
              label="学校"
              prop="schoolId"
            >
              <commonSelect
                v-model="dataForm.schoolId"
                :type-code="'SCHOOL_NAME'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="年级"
              prop="gradeId"
            >
              <commonSelect
                v-model="dataForm.gradeId"
                :type-code="'GRADE_NAME'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          type="flex"
          class="row-bg"
        >
          <el-col :span="12">
            <el-form-item
              label="班级"
              prop="classId"
            >
              <commonSelect
                v-model="dataForm.classId"
                :type-code="'CLASS_NAME'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="性别"
              prop="sex"
            >
              <commonSelect
                v-model="dataForm.sex"
                :type-code="'SEX'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          type="flex"
          class="row-bg"
        >
          <el-col :span="24">
            <el-form-item
              label="备注"
              prop="remark"
            >
              <el-input
                v-model="dataForm.remark"
                clearable
                placeholder="备注"
                maxlength="200"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5}"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="20"
          style="margin"
        >
          <el-form-item
            label="学生头像上传"
          >
            <el-col :span="24">
              <div>
                <uploadImage
                  :image-list="imageList"
                  :link-table="dataForm.linkTable"
                  :link-id="dataForm.linkId"
                  :link-field="dataForm.linkField"
                />
              </div>
            </el-col>
          </el-form-item>
        </el-row>
      </el-card>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        size="small"
        @click="isVisible = false"
      >取消</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="loading"
        @click="submitForm()"
      >确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import commonSelect from '@/components/common-select'
  import uploadImage from '@/components/upload-image'
  import { getAttachmentList } from '@/utils/common'
  import { isId } from '@/utils/validate'
  import '@/utils/directives.js'
  import { getScreenWidth } from '@/utils'
  export default {
    components: { commonSelect, uploadImage },
    props: {
      dialogVisible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: 'add'
      }
    },
    data () {
      var validateIdNumber = (rule, value, callback) => {
        if (!isId(value)) {
          callback(new Error('身份证号格式错误'))
        } else {
          callback()
        }
      }
      return {
        dataForm: this.initDataForm(),
        imageList: [],
        loading: false,
        width: getScreenWidth(),
        dataRule: {
          studentName: [
            { required: true, message: '学生姓名不能为空', trigger: 'blur' }
          ],
          studentId: [
            { required: true, message: '学籍号不能为空', trigger: 'blur' }
          ],
          idNumber: [
            { required: true, message: '身份证号不能为空', trigger: 'blur' },
            { validator: validateIdNumber, trigger: 'blur'}
          ]
        }
      }
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
          this.reset()
        }
      },
      title() {
        return this.$t('common.' + this.type)
      }
    },
    watch: {},
    mounted () {
      window.onresize = () => {
        return (() => {
          this.width = getScreenWidth()
        })()
      }
    },
    methods: {
      initDataForm() {
        return {
          studentId: '',
          studentName: '',
          idNumber: '',
          schoolId: '',
          gradeId: '',
          classId: '',
          birthday: '',
          sex: '',
          remark: '',
          linkTable: 'stu_student',
          linkId: '',
          linkField: 'studentPhoto',
          fileListIds: ''
        }
      },
      setDataForm(val) {
        if (val) {
          this.dataForm = { ...val }
          getAttachmentList("stu_student", this.dataForm.studentId, "studentPhoto").then(({data}) => {
            data.listMap.forEach(item => {
              this.imageList.push({'url': this.$http.requestUrl('/common/attachment/showFile/' + item.id + '?token=' + `${this.$cookie.get('token')}`), 'name': item.name, 'id': item.id})
            })
          })
        }
      },
      close() {
        this.$emit('close')
        this.imageList = []
      },
      reset() {
        // 先清除校验，再清除表单
        this.$refs.dataForm.clearValidate()
        this.$refs.dataForm.resetFields()
        this.dataForm = this.initDataForm()
      },
      submitForm() {
        this.dataForm.fileListIds = ''
        this.imageList.forEach(item => {
          if (item.id) {
            this.dataForm.fileListIds += item.id + ','
          }
        })
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            if (this.type === 'update') {
              this.update()
            } else {
              this.save()
            }
          } else {
            return false
          }
        })
      },
      getBirth(idCard) {
        var birthday = ""
        if(idCard != null && idCard != ""){
          if(idCard.length == 15){
            birthday = "19"+idCard.slice(6,12)
          } else if(idCard.length == 18){
            birthday = idCard.slice(6,14)
          }   
          this.dataForm.birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-")
          //通过正则表达式来指定输出格式为:1990-01-01
        }
        if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
          this.dataForm.sex = '1'
        }
        else {
          this.dataForm.sex = '0'
        }

      },
      save() {
        this.loading = true
        this.$http({
          url: this.$http.requestUrl(`/stu/student/save`),
          method: 'post',
          data: this.$http.requestData(this.dataForm)
        }).then(response => {
          const res = response.data
          if (res && res.code === 0) {
            this.isVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$emit('success')
          } else {
            this.$message.error(res.msg)
          }
          this.loading = false
        })
      },
      update() {
        this.loading = true
        this.$http({
          url: this.$http.requestUrl(`/stu/student/update`),
          method: 'post',
          data: this.$http.requestData(this.dataForm)
        }).then(response => {
          const res = response.data
          if (res && res.code === 0) {
            this.isVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$emit('success')
          } else {
            this.$message.error(res.msg)
          }
          this.loading = false
        })
      }
    }
  }
</script>
